﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using WebApiFrameworkJWTDemo.Common;
using WebApiFrameworkJWTDemo.Model;

namespace WebApiFrameworkJWTDemo.Api.Filters
{
    public class MyAuthAttribute : Attribute, IAuthorizationFilter
    {
        public bool AllowMultiple { get; }

        public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            Tuple<bool, LoginViewModel> result = JWTUtil.ValidateLogin(HttpContext.Current.Request);
            if (result.Item1)
            {
                string id = result.Item2.LoginName;
                (actionContext.ControllerContext.Controller as ApiController).User = new ApplicationUser(id, result.Item2.LoginName, result.Item2.Expiration);
                return await continuation();
            }
            return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }
    }
}